import { checkRobotByQQ } from './login.js';
import { setBotNTQQConfig, createClient, ClientNTQQ } from '../sdk/index.js';

export function setBotConfigByKey(key, val) {
    if (key == 'puppeteer') {
        // pup 不用检查 直接覆盖
        for (const item in val) {
            config[key][item] = val[item];
        }
    }
    else {
        for (const item in val) {
            // 当前仅当同属性名的时候才会覆盖默认配置
            if (Object.prototype.hasOwnProperty.call(config[key], item)) {
                config[key][item] = val[item];
            }
            else {
                // 不属于默认
                try {
                    config[key] = {};
                    config[key] = val[item];
                    console.info('KEY secess');
                }
                catch {
                    console.info('KEY err');
                }
            }
        }
    }
}
/**
 * g得到机器人基础配置
 * @param key 配置名
 * @returns 得到配置值
 */
export function getBotConfigByKey(key) {
    return config[key];
}

const conversation = {
    READY: async (data) => {
        // 设置bot信息
        setBotMsgByNtqq({
            id: data.user.id,
            name: data.user.name,
            avatar: "string",
        });
    },
    // GROUP_AT_MESSAGE_CREATE: GROUP_AT_MESSAGE_CREATE,
    // C2C_MESSAGE_CREATE: C2C_MESSAGE_CREATE,
};
export async function createAlemonByNtqq() {
    /**
     * 登录
     */
    if (await checkRobotByQQ().catch(err => {
        console.error(err);
        return false;
    })) {
        /**
         * 读取配置
         */
        const cfg = getBotConfigByKey('ntqq');
        /**
         * 发送请求
         */
        const data = await ClientNTQQ.getAuthentication(cfg.appID, cfg.secret).then(res => res.data);
        const g = {
            appID: cfg.appID,
            token: data.access_token,
            secret: cfg.secret,
            intents: ['C2C_MESSAGE_CREATE', 'GROUP_AT_MESSAGE_CREATE']
        };
        /**
         * 设置配置
         */
        setBotNTQQConfig(g);
        const bal = async () => {
            /**
             * 发送请求
             */
            const data = await ClientNTQQ.getAuthentication(cfg.appID, cfg.secret).then(res => res.data);
            g.token = data.access_token;
            /**
             * 设置配置
             */
            setBotNTQQConfig(g);
            console.info('refresh', data.expires_in, 's');
            setTimeout(bal, data.expires_in * 1000);
        };
        setTimeout(bal, data.expires_in * 1000);
        /**
         * 创建客户端
         */
        createClient(conversation, cfg?.shard ?? [0, 1]);
        return true;
    }
    return false;
}
// 客户端
export { ClientNTQQ } from '../sdk/index.js';